var db = require('../../db/db');
var publictool = require("../../publictool/publictool");

exports.port = function (req, res) {
    var requestData = '';
    req.addListener('data', function (postDataChunk) {
        requestData += postDataChunk;
    });

    req.addListener('end', function () {
        db.checkReceiptNum()
        .then(function(isok){
            if(isok){
                processEnd(req,res, requestData);
            }else{
                publictool.returnErr(res, '数据库错误', 1);
                return;
            }
        });
    });
};

function processEnd(req,res, requestData) {
    publictool.putlog(req, requestData);
    var phone = publictool.checkoutdata(res, requestData);
    if (!phone) {
        return;
    }

    var client = db.client();
    db.checkuser(client, res, false, phone.accesstoken)
        .then(function (resultvalue) {
            uploadinfo(client, resultvalue.account, phone, res);
        });
}

function uploadinfo(client, account, phone, res) {
    var addSql = 'INSERT INTO receipt(bundleid,productid,price,account,sn,receipt,timestamp,status,uuid,idfv,msg,des) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)';
    var addSqlParams = [phone.bundleId, phone.product_id, phone.price, account, phone.sn, phone.receipt, phone.timestamp, phone.status, phone.uuid, phone.idfv, phone.msg, phone.desc];

    client.query(addSql, addSqlParams, function (err, result) {
        if (err) {
            publictool.returnErr(res, '插入参数错误:' + '[INSERT ERROR] - ' + err.message, 1);
            client.end();
            return;
        }

        returnlastvalue(res, client, account);
    });
}

function returnlastvalue(res, client, account) {
    var sql = 'select product_index from receipt order by product_index DESC limit 1';
    client.query(sql, function (err, result) {
        if (err) {
            publictool.returnErr(res, '查询参数错误:' + '[SELECT ERROR] - ' + err.message, 1);
            client.end();
            return;
        }

        var value = {
            data: {
                product_index: result[0].product_index,
                account: account
            }
        };
        publictool.returnValue(res, value, '成功');
        client.end();
        return;
    });
}